<?php

namespace application\controller;

require_once("application/view/View.php");
require_once("login/controller/LoginController.php");
require_once("login/view/AddUserView.php");
require_once("login/model/AddUserDAL.php");


/**
 * Main application controller
 */
class Application {
	/**
	 * \view\view
	 * @var [type]
	 */
	private $view;

	/**
	 * @var \login\view\LoginView
	 */
	private $loginView;

	/**
	 * @var \login\controller\LoginController
	 */
	private $loginController;

	/**
	 * @var \login\view\AddUserView
	 */
	private $addUsrView;
	
	public function __construct() {
		$this->loginView = new \login\view\LoginView();
		$this->addUsrView = new \login\view\AddUserView();
		
		$this->loginController = new \login\controller\LoginController($this->loginView);
		$this->view = new \application\view\View($this->loginView);
	}
	
	/**
	 * @return \common\view\Page
	 */
	public function doFrontPage() {
		if($this->addUsrView->isCreatingUser()){
			return $this->view->getRegisterPage($this->addUsrView);
		}
		if($this->addUsrView->creatingUsr()) {
			$userName = $this->addUsrView->getNewUserName();
			$passWord = $this->addUsrView->getNewPassword();
			$repeatPassWord = $this->addUsrView->getRepeatPassword();

			$mysqli = new \mysqli("mysql08.citynetwork.se", 
								  "119958-ow88832", "Password50",
								  "119958-labb32users");
			try {
				$addUser = new \login\model\AddUserDAL($mysqli);
				$addUser->addNewUser($userName, $passWord, $repeatPassWord);
				$this->loginView->setMessage("Användare registrerad");
			} catch (\Exception $e) {
				$this->addUsrView->setMessage($e->getMessage());
				$this->addUsrView->setInputValue();
				return $this->view->getRegisterPage($this->addUsrView);
			} finally {
				$mysqli->close();
			}
		}
		$this->loginController->doToggleLogin();
		
		if ($this->loginController->isLoggedIn()) {
			$loggedInUserCredentials = $this->loginController->getLoggedInUser();
			return $this->view->getLoggedInPage($loggedInUserCredentials);	
		} else {
			return $this->view->getLoggedOutPage();
		}
	}
}
